package com.plian.system.controller.im;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.Behavioral;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.entity.im.ProjectInfo;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.im.IProjectInfoService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.im.ProjectInfoVO;
import com.plian.system.wrapper.im.ProjectInfoWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 控制器
 *
 * @author
 * @since 2019-09-27
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("api/projectinfo")
@Api(value = "ProjectInfoController", tags = "项目信息 控制器")
public class ProjectInfoController extends BaseController {

	private IProjectInfoService projectInfoService;

	private ProjectInfoWrapper projectInfoWrapper;

	private FormWorkflowService formWorkflowService;
	/**
	 * 详情
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "详情")
	@Behavioral
	public R<ProjectInfoVO> detail(@RequestBody ProjectInfo projectInfo) {
		ProjectInfo detail = projectInfoService.getOne(Condition.getQueryWrapper(projectInfo));
		return R.data(projectInfoWrapper.entityToVO(detail));
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	@ApiOperation(value = "分页")
	public ListResult<ProjectInfoVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
//		query.setAscs("order_number");
//		query.setDescs("warehousing_date");
		query.setDescs("create_time");

		QueryWrapper<ProjectInfo> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new ProjectInfo()), entityList
		);
		TokenSearch<ProjectInfo> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);
//		if (query.getPageSize() < 0){
//			queryWrapper.orderByAsc("order_number");
//		}
		IPage<ProjectInfo> pages = projectInfoService.page(Condition.getPage(query), queryWrapper);
		List<ProjectInfoVO> projectInfoVOS = projectInfoWrapper.entityToVO(pages.getRecords());
		ListResult<ProjectInfoVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(projectInfoVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	/**
	 * 所有列表
	 */
	@PostMapping("/listAll")
	@ApiOperation(value = "所有列表")
	public ListResult<ProjectInfo> listAll(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		QueryWrapper<ProjectInfo> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new ProjectInfo()), entityList
		);
		TokenSearch<ProjectInfo> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);
		List<ProjectInfo> list = projectInfoService.list(queryWrapper);
		ListResult<ProjectInfo> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(list);
		listResult.setTotal(list.size());
		return listResult;
	}
	/**
	 * 所有列表
	 */
	@PostMapping("/listAllNew")
	@ApiOperation(value = "所有列表")
	public ListResult<ProjectInfoVO> listAllNew(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		QueryWrapper<ProjectInfo> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new ProjectInfo()), entityList
		);
		TokenSearch<ProjectInfo> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);
		List<ProjectInfo> list = projectInfoService.list(queryWrapper);
		List<ProjectInfoVO> projectInfoVOS = projectInfoWrapper.entityToVO(list);

		ListResult<ProjectInfoVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(projectInfoVOS);
		listResult.setTotal(list.size());
		return listResult;
	}

	/**
	 * 项目计划执行项目列表查询
	 */
	@PostMapping("/listForPlanExecution")
	@ApiOperation(value = "项目计划执行项目列表查询")
	public ListResult<ProjectInfoVO> listForPlanExecution(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		query.setAscs("order_number");
		query.setDescs("create_time,id");

		QueryWrapper<ProjectInfo> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new ProjectInfo()), entityList
		);
		TokenSearch<ProjectInfo> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);
		if (query.getPageSize() < 0){
			queryWrapper.orderByAsc("order_number");
		}
		String fillMonth=query.getKeyword();
		IPage<ProjectInfo> pages = projectInfoService.page(Condition.getPage(query), queryWrapper);
		List<ProjectInfoVO> projectInfoVOS = projectInfoWrapper.entityToVO(pages.getRecords());
		if(StringUtil.isNotBlank(fillMonth)){
			//从月报查全年计划
			projectInfoService.addOtherFiledForPlanExecution(projectInfoVOS,fillMonth);
		}
		ListResult<ProjectInfoVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(projectInfoVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}


	/**
	 * 项目计划项目列表查询
	 */
	@PostMapping("/listForBasePlan")
	@ApiOperation(value = "项目计划项目列表查询")
	public ListResult<ProjectInfoVO> listForBasePlan(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		query.setAscs("order_number");
		query.setDescs("create_time,id");

		QueryWrapper<ProjectInfo> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new ProjectInfo()), entityList
		);
		TokenSearch<ProjectInfo> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);
		if (query.getPageSize() < 0){
			queryWrapper.orderByAsc("order_number");
		}
		String fillMonth=query.getKeyword();
		IPage<ProjectInfo> pages = projectInfoService.page(Condition.getPage(query), queryWrapper);
		List<ProjectInfoVO> projectInfoVOS = projectInfoWrapper.entityToVO(pages.getRecords());
		if(StringUtil.isNotBlank(fillMonth)){
			//从月报查询上年度实际投资、已完成投资累计总额
			projectInfoService.addOtherFiledForBasePlan(projectInfoVOS,fillMonth);
		}
		ListResult<ProjectInfoVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(projectInfoVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@ApiOperation(value = "新增或修改")
	@LogOperation("项目信息-提交")
	public R<ProjectInfo> submit(@Valid @RequestBody ProjectInfo projectInfo) {
		String checkMessage = projectInfoService.checkName(projectInfo);
		if (StringUtil.isNotBlank(checkMessage)){
			return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}
		R<ProjectInfo> result = projectInfoService.submit(projectInfo);
		if (! ((Optional.ofNullable(projectInfo.getProjectStatus()).isPresent() && projectInfo.getProjectStatus() == 1
				&& Optional.ofNullable(projectInfo.getIsNegativeProject()).isPresent() &&  projectInfo.getIsNegativeProject() == 1) ||
				(Optional.ofNullable(projectInfo.getProjectStatus()).isPresent() && projectInfo.getProjectStatus() == 3))){
			HashMap<String, Object> processVariable = new HashMap<>();
			formWorkflowService.startProcessAndSimulate(String.valueOf(projectInfo.getId()),projectInfo.getFormType(),processVariable);
		}
		return result;

	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperation(value = "删除")
	@LogOperation("项目信息-删除")
	public R remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return projectInfoService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	@GetMapping("/exportTemplateExcel")
//	@PassToken
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os){
		projectInfoService.exportTemplateExcel(response, os);
	}
	/**
	 * 覆盖导入 根据填报时间 填报单位覆盖或新增
	 */
	@PostMapping("/excelCoverImport")
	@LogOperation("项目信息-导入")
	@ApiOperation(value = "覆盖导入 根据填报时间 填报单位覆盖或新增")
	public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
		String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
		CacheUtil.put("progress","progress",progressId + "#half:hour",0);
		InputStream inputStream = multipartFile.getInputStream();
		projectInfoService.importExcel(progressId, inputStream);
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("progressId", progressId);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 导入进度查看
	 */
	@GetMapping("/progress/{progressId}")
	@ApiOperation(value = "导入进度查看")
	public ObjResult progress(@PathVariable String progressId){
		Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
		if(data != null && data instanceof String){
			if ("导入成功".equals(data)){
				ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
				PageData pd = new PageData();
				pd.put("data", 200);
				objResult.setPageData(pd);
				return objResult;
			}
			return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
		}
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("data", data);
		objResult.setPageData(pd);
		return objResult;
	}
	/**
	 * 生成excel文件
	 * @param
	 * @return
	 */
	@GetMapping("/exportImportFile")
	@ApiOperation(value = "生成excel文件")
	public ObjResult export(@RequestParam(value = "lastYear",required = false) String lastYear,
			@RequestParam(value = "superviseFlag",required = false) String superviseFlag){
		PageData pd = new PageData();
		pd.put("key", projectInfoService.export(lastYear,superviseFlag));
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 下载excel文件 并删除
	 *
	 * @param key
	 * @param response
	 */
	@GetMapping("/download/{key}")
//    @PassToken
	public void download(@PathVariable String key, HttpServletResponse response) {
		projectInfoService.download(key, response);
	}

}
